﻿using Grpc.Core;
using Grpc.Net.Client;
using IdentityModel;
using IdentityServer4.Models;
using IdentityServer4.Validation;
using ProtoBuf.Grpc.Client;
using System.Security.Claims;
using Windows.Admin.Contract;
using Windows.Admin.Contract.User.Model;

namespace Windows.Identity.Api
{
    public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
    {
        private readonly IUserGrpcService _userService;
        public ResourceOwnerPasswordValidator(IUserGrpcService userService)
        {
            _userService = userService;
        }
        public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            try
            {
                //根据context.UserName和context.Password与数据库的数据做校验，判断是否合法
                LoginRequest request = new LoginRequest();
                request.UserName = context.UserName;
                request.Password = context.Password;
                LoginResponse response = await _userService.SignInAsync(request);
                context.Result = new GrantValidationResult(response.Id.ToString(), OidcConstants.AuthenticationMethods.Password);
            }
            catch (RpcException ex)
            {
                context.Result = new GrantValidationResult(
                TokenRequestErrors.InvalidTarget,
                ex.Status.Detail);
            }
        }
    }
}
